package com.core.cloudcommon.security;

import com.core.cloudcommon.CommonCustomException;
import com.core.cloudcommon.enums.CloudSystemLoginResultCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * @author =====Lqj=====
 * @className JwtTokenUtil
 * @description JWT Token工具类
 * @create 2024/12/16 11:00
 **/
@Slf4j
@Component
public class JwtTokenUtil {

    // JWT密钥，生产环境应该从配置文件读取（至少256位）
    @Value("${jwt.secret:mySecretKeyForJWTTokenGenerationThatShouldBeAtLeast256BitsLongForSecurity}")
    private String secret;

    // Token过期时间（秒）
    @Value("${jwt.expiration:86400}") // 默认24小时
    private Long expiration;

    // 记住登录的过期时间（秒）
    @Value("${jwt.remember.expiration:2592000}") // 默认30天
    private Long rememberExpiration;

    // Token前缀
    private static final String TOKEN_PREFIX = "Bearer ";
    
    // Claims中的用户信息键
    private static final String CLAIM_KEY_USER_ID = "userId";
    private static final String CLAIM_KEY_USERNAME = "username";
    private static final String CLAIM_KEY_ORG_CODE = "orgCode";
    private static final String CLAIM_KEY_DEPART_ID = "departId";
    private static final String CLAIM_KEY_REAL_NAME = "realName";
    private static final String CLAIM_KEY_PHONE = "phone";
    private static final String CLAIM_KEY_CREATED = "created";
    private static final String CLAIM_KEY_REMEMBER_ME = "rememberMe";

    /**
     * 获取签名密钥
     */
    private SecretKey getSigningKey() {
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 从token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * 从token中获取用户ID
     */
    public Long getUserIdFromToken(String token) {
        final Claims claims = getAllClaimsFromToken(token);
        return Long.valueOf(claims.get(CLAIM_KEY_USER_ID).toString());
    }

    /**
     * 从token中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * 从token中获取创建时间
     */
    public Date getCreatedDateFromToken(String token) {
        final Claims claims = getAllClaimsFromToken(token);
        return new Date((Long) claims.get(CLAIM_KEY_CREATED));
    }

    /**
     * 从token中获取指定claim
     */
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 从token中获取所有claims
     */
    private Claims getAllClaimsFromToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            log.error("解析JWT Token失败: {}", e.getMessage());
            throw new CommonCustomException(CloudSystemLoginResultCode.CODE200022.getCode(),
                                          "Token格式错误或已过期");
        }
    }

    /**
     * 检查token是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }

    /**
     * 生成token
     */
    public String generateToken(UserInfo userInfo, Boolean rememberMe) {
        Map<String, Object> claims = new HashMap<>();
        claims.put(CLAIM_KEY_USER_ID, userInfo.getId());
        claims.put(CLAIM_KEY_USERNAME, userInfo.getUserName());
        claims.put(CLAIM_KEY_ORG_CODE, ""); // 暂时设为空，避免循环依赖
        claims.put(CLAIM_KEY_DEPART_ID, userInfo.getDepartId());
        claims.put(CLAIM_KEY_REAL_NAME, userInfo.getRealName());
        claims.put(CLAIM_KEY_PHONE, userInfo.getPhone());
        claims.put(CLAIM_KEY_CREATED, new Date().getTime());
        claims.put(CLAIM_KEY_REMEMBER_ME, rememberMe);

        return generateToken(claims, userInfo.getUserName(), rememberMe);
    }

    /**
     * 生成token
     */
    private String generateToken(Map<String, Object> claims, String subject, Boolean rememberMe) {
        final Date createdDate = new Date();
        final Date expirationDate = calculateExpirationDate(createdDate, rememberMe);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }

    /**
     * 计算过期时间
     */
    private Date calculateExpirationDate(Date createdDate, Boolean rememberMe) {
        long exp = Boolean.TRUE.equals(rememberMe) ? rememberExpiration : expiration;
        return new Date(createdDate.getTime() + exp * 1000);
    }

    /**
     * 刷新token
     */
    public String refreshToken(String token) {
        try {
            final Claims claims = getAllClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, new Date().getTime());
            
            Boolean rememberMe = (Boolean) claims.get(CLAIM_KEY_REMEMBER_ME);
            return generateToken(claims, claims.getSubject(), rememberMe);
        } catch (Exception e) {
            log.error("刷新JWT Token失败: {}", e.getMessage());
            throw new CommonCustomException(CloudSystemLoginResultCode.CODE200023.getCode(), 
                                          "Token刷新失败");
        }
    }

    /**
     * 验证token
     */
    public Boolean validateToken(String token, UserInfo userInfo) {
        try {
            final String username = getUsernameFromToken(token);
            final Long userId = getUserIdFromToken(token);

            return (username.equals(userInfo.getUserName())
                    && userId.equals(userInfo.getId())
                    && !isTokenExpired(token));
        } catch (Exception e) {
            log.error("验证JWT Token失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 从token中构建用户信息
     */
    public UserInfo getUserFromToken(String token) {
        try {
            final Claims claims = getAllClaimsFromToken(token);

            SimpleUserInfo userInfo = new SimpleUserInfo();
            userInfo.setId(Long.valueOf(claims.get(CLAIM_KEY_USER_ID).toString()));
             userInfo.setUserName(claims.getSubject());
            userInfo.setRealName((String) claims.get(CLAIM_KEY_REAL_NAME));
            userInfo.setPhone((String) claims.get(CLAIM_KEY_PHONE));

            if (claims.get(CLAIM_KEY_DEPART_ID) != null) {
                userInfo.setDepartId(Long.valueOf(claims.get(CLAIM_KEY_DEPART_ID).toString()));
            }

            return userInfo;
        } catch (Exception e) {
            log.error("从JWT Token构建用户信息失败: {}", e.getMessage());
            throw new CommonCustomException(CloudSystemLoginResultCode.CODE200022.getCode(), 
                                          "Token格式错误");
        }
    }

    /**
     * 检查token是否需要刷新
     * 如果token在30分钟内过期，则需要刷新
     */
    public Boolean shouldRefreshToken(String token) {
        try {
            final Date expirationDate = getExpirationDateFromToken(token);
            final Date now = new Date();
            
            // 如果在30分钟内过期，则需要刷新
            return expirationDate.getTime() - now.getTime() < 30 * 60 * 1000;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取token剩余有效时间（秒）
     */
    public Long getTokenRemainingTime(String token) {
        try {
            final Date expirationDate = getExpirationDateFromToken(token);
            final Date now = new Date();
            
            long remaining = (expirationDate.getTime() - now.getTime()) / 1000;
            return Math.max(0, remaining);
        } catch (Exception e) {
            return 0L;
        }
    }

    /**
     * 清理token前缀
     */
    public String cleanToken(String token) {
        if (token != null && token.startsWith(TOKEN_PREFIX)) {
            return token.substring(TOKEN_PREFIX.length());
        }
        return token;
    }

    /**
     * 添加token前缀
     */
    public String addTokenPrefix(String token) {
        if (token != null && !token.startsWith(TOKEN_PREFIX)) {
            return TOKEN_PREFIX + token;
        }
        return token;
    }
}
